<template>
  <div class="project-container">
    <!-- 项目头部信息 -->
    <div class="project-header">
      <div class="project-title-row">
        <div class="project-title">
          <!-- 项目状态 -->
          <span class="project-badge">{{ project?.['686df6df33681903aca10690'] || '' }}</span>
          <!-- 项目名称 -->
          <el-tooltip
            :content="project?.['686df5d4fa20ded33c042478'] || ''"
            placement="top"
            :disabled="
              !project?.['686df5d4fa20ded33c042478'] ||
              (project?.['686df5d4fa20ded33c042478'] || '').length <= 20
            "
            effect="light"
            :show-after="300"
          >
            <h1>{{ project?.['686df5d4fa20ded33c042478'] || '' }}</h1>
          </el-tooltip>
        </div>
        <div class="title-actions">
          <!-- 客户名称 -->
          <span class="company-text">{{ getCustomer(project) }}</span>
          <!-- 当前项目需求类型-->
          <button
            class="action-btn"
            :class="getRoleClass(value['type'])"
            v-for="value in itemList"
            :key="value['type']"
          >
            {{ value['type'] }}
          </button>
        </div>

        <div class="return-btn">
          <el-button type="default" @click="handleReturn">返回项目列表</el-button>
        </div>
      </div>
      <div class="project-meta">
        <span class="project-info">
          <span class="project-item">{{
            getDate(project?.['686e317ee9211671b47589db'] || '')
          }}</span>
          <span class="project-item">|</span>
          <span class="project-item">
            {{
              diffDays({
                a: project?.['686e317ee9211671b47589db'] || '',
                b: project?.['686f5c562307310db1c4eea1'] || '',
              })
            }}
          </span>
          <span class="project-item" style="margin-left: 40px">{{
            project?.['6876ff515d31544df2c58975'] || ''
          }}</span>
        </span>
      </div>

      <!-- 需求栏 -->
      <div class="requirements">
        <div class="req-left"></div>
        <div class="req-center"></div>
        <div class="req-right">
          <div>
            <button class="export-btn" @click="exportDocuments">导出文档</button>
            <button v-if="isExportMode" class="exit-export-btn" @click="exitExportMode">
              退出导出状态
            </button>
            <!-- 当项目状态为已选中时隐藏确认选中按钮 -->
            <button
              v-if="!isProjectSelected && !isExportMode"
              class="recommend-btn"
              :class="{
                'return-btn-style': false,
              }"
              @click="handleConfirmSelection"
            >
              确认选中
            </button>
          </div>

          <div class="req-roles">
            <span class="req-role">已选择</span>
            <span class="req-role" v-for="(count, roleType) in selectedRolesStats" :key="roleType">
              {{ roleType }}: {{ count }}人
            </span>
            <span class="req-role_red">共{{ totalSelected }}人</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-area">
      <!-- 左侧分类菜单 -->
      <div class="category-sidebar">
        <div
          v-for="item in itemList"
          :key="item.type"
          class="category-item"
          :class="{ active: selectedCategory === item.type }"
          @click="selectCategory(item.type)"
        >
          <span class="category-text">{{ item.type }}</span>
        </div>
      </div>

      <!-- 右侧人员卡片区域 -->
      <div class="role_card">
        <div class="role_top">
          <div>
            <span>{{ selectedCategory }} X{{ getCurrentCategoryPersonNum() }}</span>
          </div>
          <div class="role_card_top">
            <el-tooltip
              :content="getCurrentCategoryDemand()"
              placement="top"
              :disabled="!getCurrentCategoryDemand() || getCurrentCategoryDemand().length <= 20"
              effect="light"
              :show-after="300"
            >
              <span class="req-constraints">要求：{{ getCurrentCategoryDemand() }}</span>
            </el-tooltip>
            <el-tooltip
              :content="getCurrentCategoryWork()"
              placement="top"
              :disabled="!getCurrentCategoryWork() || getCurrentCategoryWork().length <= 20"
              effect="light"
              :show-after="300"
            >
              <span class="req-work">工作内容：{{ getCurrentCategoryWork() }}</span>
            </el-tooltip>
          </div>
        </div>
        <div class="personnel-grid">
          <div
            v-for="person in filteredCandidateList"
            :key="person.rowid"
            class="personnel-card"
            @click="showRoleDetail(person['rowid'])"
          >
            <!-- 状态标签 - 显示已选中或已退回 -->
            <div
              v-if="getRoleStatusLabel(person)"
              class="selected-label"
              :class="getRoleStatusClass(person)"
            >
              {{ getRoleStatusLabel(person) }}
            </div>

            <!-- 选择框 - 当项目状态为已选中时隐藏，但在导出模式下显示 -->
            <div
              v-if="(getRoleStatusLabel(person) !== '已选中' && !isProjectSelected) || isExportMode"
              class="selection-mark"
              :class="{
                selected: person.userSelected,
                disabled: !person.userSelected && isCurrentCategoryFull && !isExportMode,
              }"
              @click.stop="handleSelectionClick(person.rowid)"
            ></div>

            <!-- 头像区域 -->
            <div class="avatar-container">
              <div
                class="avatar"
                :style="{
                  backgroundImage: person['687633c7ef700e94a0d82b59']
                    ? `url(${JSON.parse(person['687633c7ef700e94a0d82b59'])[0]['DownloadUrl']})`
                    : 'none',
                }"
              ></div>
              <div class="deal-badge">已成交{{ person['6875b364096a775fc5322bd7'] || 0 }}单</div>
            </div>

            <!-- 人员信息 -->
            <div class="personnel-info">
              <div class="name-section">
                <span class="name">{{ person['686e0c6fd9147824a38a6294'] }}</span>
                <span
                  class="gender"
                  :class="
                    person['686e0c6fd9147824a38a6295'] === '2d5e8f66-b757-4a60-b7e7-e7c2a3c716bf'
                      ? 'female'
                      : 'male'
                  "
                >
                  {{
                    person['686e0c6fd9147824a38a6295'] == '2d5e8f66-b757-4a60-b7e7-e7c2a3c716bf'
                      ? '♀'
                      : '♂'
                  }}
                </span>
                <span class="location">
                  {{ getProvinceAndCity(person['686e0f429104eb90ad4247a3']) }} ·
                  {{
                    person['686e0f429104eb90ad4247a4'] === '470a70a3-4fc3-4c4c-bea6-3bd2a2b7556c'
                      ? '全国'
                      : '仅本地'
                  }}
                </span>
              </div>

              <div class="stats">
                <div class="stat-item">
                  <span class="stat-value">{{ person['686e0f429104eb90ad4247a5'] }}cm</span>
                  <span class="stat-label">身高</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ person['686e0f429104eb90ad4247a6'] }}kg</span>
                  <span class="stat-label">体重</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ person['688051358c409b88b8519759'] }}</span>
                  <span class="stat-label">三围</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ person['686e0f429104eb90ad4247a8'] }}</span>
                  <span class="stat-label">鞋码</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 角色详情弹框 -->
    <RoleDetailDialog v-model:visible="dialogVisible" :role-data="selectedRole" />

    <!-- 确认选中对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      :title="confirmDialogTitle"
      width="500px"
      :before-close="handleDialogBeforeClose"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :show-close="true"
      :center="true"
    >
      <div class="confirm-dialog-content">
        <div class="confirm-dialog-text" v-html="confirmDialogContent.replace(/\n/g, '<br>')"></div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleConfirmDialogCancel">
            {{ confirmDialogButtons.cancel }}
          </el-button>
          <el-button
            :type="confirmDialogType === 'success' ? 'primary' : 'primary'"
            @click="handleConfirmDialogConfirm"
            :class="confirmDialogType === 'success' ? 'el-button--success' : ''"
          >
            {{ confirmDialogButtons.confirm }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, h } from 'vue'
import { useRoute } from 'vue-router'
import { apiService, ApiService } from '@/utils/api'
import RoleDetailDialog from '@/components/RoleDetailDialog.vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAreaName, getProvinceAndCity } from '@/utils/areaCode'
import router from '@/router'

// 获取路由参数
const route = useRoute()

// 获取用户状态管理实例

const userStore = useUserStore()

const itemList = ref([])

const demand = ref([])
const loading = ref(false) // 保留用于其他可能的加载状态
const candidateList = ref([]) // 存储候选人列表
const selectedClusterId = ref('all') // 当前选中的群头ID，'all'表示全部
const selectedCategory = ref('') // 当前选中的分类，默认礼仪

const selectRoleList = ref([])
const selectedNameSet = ref(new Set())

const givebackRoleList = ref([])

const demandToRole = ref([]) // 初始化为空数组而不是空对象

// 标签分页
const tabPageIndex = ref(0)
const tabsPerPage = 8 // 每页展示的群头数量
const visibleTabs = computed(() => {
  // 只包含群头名称的列表
  const list = detailsArr.value.map((cluster) => cluster.clusterName)
  const start = tabPageIndex.value * tabsPerPage
  const end = start + tabsPerPage
  return list.slice(start, end)
})

const nextTabPage = () => {
  const total = detailsArr.value.map((cluster) => cluster.clusterName).length
  const maxPage = Math.max(0, Math.ceil(total / tabsPerPage) - 1)
  tabPageIndex.value = tabPageIndex.value >= maxPage ? 0 : tabPageIndex.value + 1
}

// const project = ref(route.query.project ? JSON.parse(route.query.project) : null)
const project = ref({})

// 弹框相关数据
const dialogVisible = ref(false)
const selectedRole = ref({})

const roleList = ref([])

const detailsArr = ref([])

const demandList = ref([])

const demandSet = ref(new Set())
const workSet = ref(new Set())

const role = ref([])
const groupedDemand = ref({}) // 根据群头名称分组后的需求

// 计算属性：根据选中的群头和分类过滤候选人列表
const filteredCandidateList = computed(() => {
  // 返回所有候选人，不再过滤掉无状态标签的人员
  const filteredList = candidateList.value.filter((person) => {
    const label = getRoleStatusLabel(person)
    return label !== '已退回' // 只过滤掉"已退回"状态的人员
  })

  // 根据标签优先级排序：已选中 -> 普通
  const getPriority = (person) => {
    const label = getRoleStatusLabel(person)
    if (label === '已选中') return 0
    return 1
  }

  return filteredList.sort((a, b) => {
    const pa = getPriority(a)
    const pb = getPriority(b)
    if (pa !== pb) return pa - pb
    return 0
  })
})

// 计算属性：去重后的角色类型列表
const uniqueRoleTypes = computed(() => {
  const uniqueRoles = []
  const seenRoles = new Set()

  roleList.value.forEach((item) => {
    const roleType = item['type']
    console.log('roleType:', roleType)

    if (roleType && !seenRoles.has(roleType)) {
      seenRoles.add(roleType)
      uniqueRoles.push(item)
    }
  })

  return uniqueRoles
})

// 计算属性：获取当前选择分类的要求
const currentCategoryRequirements = computed(() => {
  // 将 demandSet 转换为数组并返回
  return Array.from(demandSet)
})

// 计算属性：获取当前选择分类的工作内容
const currentCategoryWorkContent = computed(() => {
  if (!selectedCategory.value) return ''

  const currentRoleType = uniqueRoleTypes.value.find(
    (role) => role['686f2308f11e0126aeb367d7'] === selectedCategory.value,
  )

  return currentRoleType ? currentRoleType['686e48ea1f42f2639e1b907f'] || '' : ''
})

// 计算属性：获取已选中的角色类型和人数统计（跨群头和分类）
const selectedRolesStats = computed(() => {
  const roleStats = {}

  // 遍历所有角色类型，统计所有选中的角色（包含用户本次勾选与已标记"已选中"的卡片）
  roleList.value.forEach((roleType) => {
    if (roleType.list && Array.isArray(roleType.list)) {
      roleType.list.forEach((person) => {
        const key = `${roleType.type}:${person.rowid}`
        const isUserSelected = !!globalSelectionState.value[key]
        const isAlreadySelected = getRoleStatusLabel(person, roleType.type) === '已选中'

        if (isUserSelected || isAlreadySelected) {
          const type = roleType.type || '未知'
          if (!roleStats[type]) {
            roleStats[type] = 0
          }
          roleStats[type]++
        }
      })
    }
  })

  return roleStats
})

// 计算属性：获取当前选择分类的已选择人数（包含手动勾选和已选中标签）
const currentSelectedCount = computed(() => {
  if (!selectedCategory.value) return 0

  // 找到当前分类的角色数据
  const currentRoleType = roleList.value.find(
    (roleType) => roleType.type === selectedCategory.value,
  )
  if (!currentRoleType || !currentRoleType.list) return 0

  let count = 0

  // 统计当前分类中已选中的人数（包含手动勾选和已选中标签）
  currentRoleType.list.forEach((person) => {
    const key = `${selectedCategory.value}:${person.rowid}`
    const isUserSelected = !!globalSelectionState.value[key]
    const isAlreadySelected = getRoleStatusLabel(person) === '已选中'
    if (isUserSelected || isAlreadySelected) {
      count++
    }
  })

  return count
})

//选择推荐人
const selectRecommendedPersons = async (type) => {
  console.log('登录用户 rowid:', userStore.userRowid)

  // 按角色类型分组
  const roleGroups = {
    ceremony: [], // 礼仪
    partTime: [], // 兼职
    teamLead: [], // 带队
  }

  // 遍历所有角色类型，收集每个分类中已选中的人员
  roleList.value.forEach((roleType) => {
    if (roleType.list && Array.isArray(roleType.list)) {
      roleType.list.forEach((person) => {
        const key = `${roleType.type}:${person.rowid}`
        const isUserSelected = !!globalSelectionState.value[key]
        const isAlreadySelected = getRoleStatusLabel(person) === '已选中'

        if (isUserSelected || isAlreadySelected) {
          // 映射分类名称到英文键名
          let englishKey = ''
          if (roleType.type === '礼仪') englishKey = 'ceremony'
          else if (roleType.type === '兼职') englishKey = 'partTime'
          else if (roleType.type === '带队') englishKey = 'teamLead'

          if (englishKey && roleGroups[englishKey]) {
            roleGroups[englishKey].push(person.rowid)
          }
        }
      })
    }
  })

  console.log('按角色类型分组的结果:', roleGroups)

  try {
    // 一次性提交所有角色分组数据
    console.log('正在提交角色分组数据:', roleGroups)

    console.log('提交数据:', {
      roleGroups: roleGroups, // 传递角色分组对象
      projectRowid: project.value['rowid'],
      userRowid: userStore.userRowid,
    })

    const result = await apiService.selectRole({
      roleGroups: roleGroups, // 传递角色分组对象
      projectRowid: project.value['rowid'],
      userRowid: userStore.userRowid,
      type: type,
    })
    if (type === '退回') {
      ElMessage.success('您已选择退回平台补充资料，平台将补充更多资料供您选择')
    } else {
      ElMessage.success(`角色提交成功`)
    }

    console.log('角色提交结果:', result)

    // 推荐成功后刷新页面获取最新数据
    setTimeout(() => {
      window.location.reload()
    }, 1500) // 延迟1.5秒后刷新，让用户看到成功提示
  } catch (error) {
    console.error('提交推荐人员失败:', error)
    ElMessage.error('提交失败，请重试')
  }
}

const returnok = async () => {
  console.log('returnok')
  // 检查所有角色类型的人数是否都符合需求
  // 使用 itemList 数据源替代 uniqueRoleTypes 和 demandToRole
  for (const item of itemList.value) {
    const roleTypeName = item.type
    const currentSelectedCount = selectedRolesStats.value[roleTypeName] || 0
    const requiredCount = parseInt(item.personNum) || 0

    console.log('currentSelectedCount:', currentSelectedCount)
    console.log('requiredCount:', requiredCount)

    // 如果任何一个角色类型的人数超过需求，就阻止提交
    if (currentSelectedCount > requiredCount) {
      console.log('handlereturnokGetMore')
      ElMessage.warning(`${roleTypeName}类别人数已满，请先取消其他选择`)
      return
    }
  }

  // 设置确认选中对话框
  confirmDialogTitle.value = '确认选中'
  confirmDialogContent.value = `是否确认选中您已选择的${totalSelected.value}位候选人`
  confirmDialogType.value = 'success'
  confirmDialogButtons.value = {
    confirm: '确认选中',
    cancel: '取消',
  }
  confirmDialogCallback.value = async () => {
    await selectRecommendedPersons('选中')
  }
  confirmDialogVisible.value = true
}

const getRoleData = () => {
  console.log('=== 已选中的角色信息 ===')
  const list = []

  // 遍历所有角色类型，查找已选中的角色
  roleList.value.forEach((roleType) => {
    if (roleType.list && Array.isArray(roleType.list)) {
      roleType.list.forEach((person) => {
        const roleStatusLabel = getRoleStatusLabel(person, roleType.type)
        const key = `${roleType.type}:${person.rowid}`
        const isUserSelected = !!globalSelectionState.value[key]

        // 如果状态为"已选中"或者选择框被选中，都加入列表
        if (roleStatusLabel === '已选中' || isUserSelected) {
          list.push({
            ...person,
            角色类型: roleType.type,
            选择方式: roleStatusLabel === '已选中' ? '已选中标签' : '选择框选中',
            状态: roleStatusLabel === '已选中' ? '已选中' : '待确认',
          })
        }
      })
    }
  })

  // 同时打印已选中角色列表的统计信息
  console.log('已选中角色列表:', list)
  console.log('已选中角色总数:', list.length)

  // 按角色类型分组统计
  const roleStats = {}
  list.forEach((person) => {
    const type = person.角色类型
    if (!roleStats[type]) {
      roleStats[type] = { 总数: 0, 已选中: 0, 待确认: 0 }
    }
    roleStats[type].总数++
    if (person.状态 === '已选中') {
      roleStats[type].已选中++
    } else {
      roleStats[type].待确认++
    }
  })

  console.log('按角色类型统计:', roleStats)
  console.log('=== 已选中角色信息结束 ===')
}

// 处理确认选择按钮点击
const handleConfirmSelection = async () => {
  console.log('确认选中')

  getRoleData()

  console.log(selectedRolesStats.value)

  const selectedCount = totalSelected.value

  // 新增：当总已选人数小于总需求人数时，弹出自定义确认弹窗
  // 使用 itemList 数据源替代 demandToRole
  const requiredMap = (itemList.value || []).reduce((acc, item) => {
    const type = item && item.type
    const total = Number(item && item.personNum) || 0
    if (type) acc[type] = total
    return acc
  }, {})
  const totalRequired = Object.values(requiredMap).reduce((a, b) => a + b, 0)

  console.log('selectedCount：', selectedCount)
  console.log('totalRequired', totalRequired)

  if (selectedCount < totalRequired) {
    const roleTypes = Array.from(new Set((itemList.value || []).map((r) => r.type)))

    const lines = roleTypes
      .map((type) => {
        const need = requiredMap[type] || 0
        const sel = (selectedRolesStats.value && selectedRolesStats.value[type]) || 0
        const text = need > 0 ? `${type}:需要${need}人，已选${sel}人` : `${type}:无需选择`
        return text
      })
      .join('\n')

    // 设置对话框内容
    confirmDialogTitle.value = '确认选择'
    confirmDialogContent.value = `您需选人${totalRequired}人，已选${selectedCount}人，选人明细如下:\n\n${lines}\n\n可以 继续选人，或 获取更多人选\n\n获取更多:已选中人选会保持选中，平台将补充更多人选供您选择`
    confirmDialogType.value = 'info'
    confirmDialogButtons.value = {
      confirm: '继续选人', // 交换位置：确认按钮改为"继续选人"
      cancel: '获取更多', // 交换位置：取消按钮改为"获取更多"
    }
    confirmDialogCallback.value = () => {
      // 确认按钮现在执行"继续选人"的逻辑（即关闭对话框，不做任何操作）
      confirmDialogVisible.value = false
    }
    confirmDialogVisible.value = true
    return
  }

  if (selectedCount === totalRequired) {
    returnok()
    return
  }
}

// 处理对话框确认按钮点击
const handleConfirmDialogConfirm = async () => {
  if (confirmDialogCallback.value) {
    await confirmDialogCallback.value()
  }
  // 如果confirmDialogCallback没有设置，直接关闭对话框
  if (!confirmDialogCallback.value) {
    confirmDialogVisible.value = false
  }
}

// 处理对话框取消按钮点击
const handleConfirmDialogCancel = () => {
  // 只有主动点击取消按钮时才执行"获取更多"逻辑
  if (confirmDialogTitle.value === '确认选择' && confirmDialogButtons.value.cancel === '获取更多') {
    handleGetMore()
  }
  confirmDialogVisible.value = false
}

// 退回平台补充资料的处理函数
const handleReturnToPlatform = async () => {
  const selectedCount = currentSelectedCount.value

  if (selectedCount === 0) {
    ElMessage.warning('请先选择要操作的人员')
    return
  }
  try {
    // 这里添加退回平台的API调用逻辑
    console.log('执行退回平台补充资料逻辑')

    try {
      // 确认退回逻辑
      await ElMessageBox.confirm(`是否退回选中您已选择的${selectedCount}位候选人`, '确认退回', {
        confirmButtonText: '确认退回',
        cancelButtonText: '取消',
        type: 'success',
        confirmButtonClass: 'el-button--success',
      })

      // 执行确认退回逻辑
      await selectRecommendedPersons('退回')
    } catch (error) {
      // 用户取消操作
      console.log('用户取消操作')
    }

    // 清空选择状态
    filteredCandidateList.value.forEach((person) => {
      person.userSelected = false
    })
    globalSelectionState.value = {}
  } catch (error) {
    console.error('退回平台失败:', error)
  }
}

const handleReturn = () => {
  router.replace({ name: 'project' })
}

// 计算属性：获取已选中的总人数（跨群头和分类）
const totalSelected = computed(() => {
  const uniqueKeys = new Set()

  // 以 roleList 为准，统计"手动勾选"或"已选中标签"的唯一人选
  roleList.value.forEach((roleType) => {
    if (roleType.list && Array.isArray(roleType.list)) {
      roleType.list.forEach((person) => {
        const key = `${roleType.type}:${person.rowid}`
        const isUserSelected = !!globalSelectionState.value[key]
        const isAlreadySelected = getRoleStatusLabel(person, roleType.type) === '已选中'
        if (isUserSelected || isAlreadySelected) {
          uniqueKeys.add(key)
        }
      })
    }
  })

  return uniqueKeys.size
})

// 计算属性：判断当前角色类别是否已选满（包含已标记"已选中"的卡片）
const isCurrentCategoryFull = computed(() => {
  if (!selectedCategory.value || isExportMode.value) return false

  // 获取当前类别已选择的人数（手动勾选 或 已为"已选中"的卡片）
  const currentSelectedCount = filteredCandidateList.value.filter(
    (person) => person.userSelected || getRoleStatusLabel(person) === '已选中',
  ).length

  // 获取当前类别需要的总人数 - 使用 getCurrentCategoryPersonNum()
  const requiredCount = getCurrentCategoryPersonNum()

  return currentSelectedCount >= requiredCount
})

// 计算属性：判断项目状态是否为已选中
const isProjectSelected = computed(() => {
  const projectStatus = project.value?.['686df6df33681903aca10690']
  return projectStatus === '已选中'
})

const diffDays = (obj) => {
  // 把对象里的值取出来并转成 Date
  const [d1, d2] = Object.values(obj).map((v) => new Date(v))
  // 毫秒差 → 天数（向上取整，不足一天也算一天）
  const days = Math.ceil(Math.abs(d2 - d1) / (1000 * 60 * 60 * 24))
  return `${days}天`
}

// 全局选择状态存储，跨群头和分类保存所有选中的角色
const globalSelectionState = ref({})

// 保存选择状态到全局存储
const saveToGlobalSelection = () => {
  filteredCandidateList.value.forEach((person) => {
    const key = `${selectedCategory.value}:${person.rowid}`
    if (person.userSelected) {
      globalSelectionState.value[key] = true
    } else {
      delete globalSelectionState.value[key]
    }
  })
}

// 从全局存储恢复选择状态
const restoreFromGlobalSelection = () => {
  candidateList.value.forEach((person) => {
    person.userSelected = !!globalSelectionState.value[`${selectedCategory.value}:${person.rowid}`]
  })
}

const getDate = (str) => {
  if (!str) return ''
  const result = str.split(' ')[0].replace(/-/g, '.')
  return result
}

const getRequire = (data) => {
  const setVal = data && data.value instanceof Set ? data.value : data
  if (!setVal) return ''
  return Array.from(setVal).join('、')
}

const getRoleClass = (name) => {
  const map = {
    礼仪: 'ceremony',
    兼职: 'part-time',
    带队: 'team-lead',
  }
  return map[name] || ''
}

// 选择分类
const selectCategory = (category) => {
  selectedCategory.value = category

  // 找到对应的角色类型数据
  const selectedRoleType = roleList.value.find((item) => item['type'] === category)

  // 先清空当前候选人列表
  candidateList.value = []

  if (selectedRoleType) {
    // 将选中分类的数据添加到候选人列表
    selectedRoleType.list.forEach((person) => {
      candidateList.value.push({
        ...person,
        userSelected: false,
      })
    })

    // 恢复已选中人员的状态
    candidateList.value.forEach((person) => {
      const personName = person['686e0c6fd9147824a38a6294']

      // 如果该人员在已选中姓名集合中，恢复其状态
      if (personName && selectedNameSet.value.has(personName)) {
        person['68761720096a775fc5332e94'] = '已选中'
        if (person.rowid) {
          globalSelectionState.value[person.rowid] = true
        }
      }

      // 恢复全局选择状态
      if (globalSelectionState.value[`${selectedCategory.value}:${person.rowid}`]) {
        person.userSelected = true
      }
    })

    console.log('roleList:', roleList.value)
    console.log('选择分类:', candidateList.value)
  }
}

//选择卡片
const toggleSelection = (personRowid) => {
  const person = candidateList.value.find((p) => p.rowid === personRowid)
  if (person) {
    person.userSelected = !person.userSelected
    // 移除设置已选中标签的逻辑，只有getRoleStatus方法才能设置
    // 更新全局选择状态（按分类独立）
    const key = `${selectedCategory.value}:${personRowid}`
    if (person.userSelected) {
      globalSelectionState.value[key] = true
    } else {
      delete globalSelectionState.value[key]
    }
  }
}

// 处理选择框点击事件
const handleSelectionClick = (personRowid) => {
  const person = candidateList.value.find((p) => p.rowid === personRowid)
  if (!person) return

  // 在导出模式下，允许自由选择，不受人数限制
  if (isExportMode.value) {
    toggleSelection(personRowid)
    return
  }

  // 如果当前类别已选满且该人员未被选中，则不允许选择
  if (!person.userSelected && isCurrentCategoryFull.value) {
    console.log('handleSelectionClick')

    ElMessage.warning(`${selectedCategory.value}类别人数已满，请先取消其他选择`)
    return
  }

  // 执行正常的选择逻辑
  toggleSelection(personRowid)
}

// 进入导出模式
const enterExportMode = () => {
  isExportMode.value = true

  // 清空所有选择框
  candidateList.value.forEach((person) => {
    person.userSelected = false
  })

  // 清空全局选择状态
  globalSelectionState.value = {}

  // 遍历所有角色类型，将已选中状态的人员设置为选中
  roleList.value.forEach((roleType) => {
    if (roleType.list && Array.isArray(roleType.list)) {
      roleType.list.forEach((person) => {
        if (getRoleStatusLabel(person, roleType.type) === '已选中') {
          // 更新全局选择状态（按分类独立）
          const key = `${roleType.type}:${person.rowid}`
          globalSelectionState.value[key] = true
        }
      })
    }
  })

  // 如果当前有候选人列表，也要更新当前分类的选中状态
  candidateList.value.forEach((person) => {
    if (getRoleStatusLabel(person) === '已选中') {
      person.userSelected = true
    }
  })

  ElMessage.info('已进入文档导出模式，请选择要导出文档的人员')
}

// 退出导出模式
const exitExportMode = () => {
  isExportMode.value = false

  // 清空所有选择框
  candidateList.value.forEach((person) => {
    person.userSelected = false
  })

  // 清空全局选择状态
  globalSelectionState.value = {}

  ElMessage.info('已退出文档导出模式')
}

// 修改导出函数，支持任何文件类型
const exportDocuments = async () => {
  if (!isExportMode.value) {
    // 进入导出模式
    enterExportMode()
    return
  }

  // 导出模式下的逻辑
  // 获取已选中状态的人员 + 当前选择框被选中的人员
  const exportPersons = []

  // 1. 添加状态为"已选中"的人员
  candidateList.value.forEach((person) => {
    if (getRoleStatusLabel(person) === '已选中') {
      exportPersons.push(person)
    }
  })

  // 2. 添加当前选择框被选中的人员（去重）
  const selectedPersons = candidateList.value.filter((person) => person.userSelected)
  selectedPersons.forEach((person) => {
    // 检查是否已经存在（避免重复）
    const exists = exportPersons.some((p) => p.rowid === person.rowid)
    if (!exists) {
      exportPersons.push(person)
    }
  })

  if (exportPersons.length === 0) {
    console.log('⚠️ 没有选中任何人员')
    ElMessage.warning('请先选择要导出的人员')
    return
  }

  console.log('exportPersons')
  console.log(exportPersons)

  const documentArr = exportPersons.map((item) => ({
    name: item['686e0c6fd9147824a38a6294'],
    urldata: item['68b71114da018971cf8f6133'],
  }))
  console.log('documentArr:', documentArr)

  const documentUrlArr = documentArr
    .map((item) => {
      if (item.urldata) {
        try {
          // 首先尝试解析为JSON（兼容旧格式）
          const parsedData = JSON.parse(item.urldata)
          if (Array.isArray(parsedData) && parsedData.length > 0) {
            return {
              name: item.name,
              url: parsedData[0].DownloadUrl,
            }
          }
        } catch (error) {
          // 如果JSON解析失败，说明urldata直接就是URL字符串
          console.log('urldata不是JSON格式，直接作为URL使用:', item.urldata)
          return {
            name: item.name,
            url: item.urldata,
          }
        }
      }
      return null
    })
    .filter(Boolean)

  console.log('documentUrlArr:', documentUrlArr)

  if (documentUrlArr.length === 0) {
    console.log('⚠️ 没有找到可下载的文档文件')
    ElMessage.warning('选中的人员没有可下载的文档文件')
    return
  }

  // 批量下载文档文件
  await downloadMultipleDocuments(documentUrlArr)

  // 导出完成后清空选中卡片的选择框
  candidateList.value.forEach((person) => {
    person.userSelected = false
  })

  // 清空全局选择状态
  globalSelectionState.value = {}

  // 导出完成后退出导出模式
  isExportMode.value = false
}

// 批量下载多个文档文件
const downloadMultipleDocuments = async (documentData) => {
  try {
    console.log('开始批量下载文档文件...')

    // 逐个下载文档文件
    for (let i = 0; i < documentData.length; i++) {
      const item = documentData[i]

      console.log(`正在下载: ${item.name}`)

      try {
        // 使用直接链接下载（避免CORS问题）
        await downloadWithDirectLink(item.url, item.name)

        console.log(`✅ ${item.name} 下载完成`)

        // 添加延迟，避免浏览器阻止多个下载
        if (i < documentData.length - 1) {
          await new Promise((resolve) => setTimeout(resolve, 500))
        }
      } catch (downloadError) {
        console.error(`下载 ${item.name} 失败:`, downloadError)
      }
    }

    console.log('所有文档文件下载完成！')

    // 显示成功提示
    ElMessage.success(`成功导出 ${documentData.length} 个文档文件！`)
  } catch (error) {
    console.error('文档下载失败:', error)
  }
}

// 使用直接链接下载（支持任何文件类型）
const downloadWithDirectLink = async (url, fileName) => {
  try {
    console.log(`开始下载文件: ${fileName}, URL: ${url}`)

    // 使用带凭证的fetch请求
    const response = await fetch(url, {
      method: 'GET',
      mode: 'cors',
    })

    if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`)

    // 获取内容类型
    const contentType = response.headers.get('content-type')
    console.log(`文件内容类型: ${contentType}`)

    // 获取blob
    const blob = await response.blob()
    console.log(`文件大小: ${blob.size} bytes`)

    // 从URL中提取文件名和扩展名
    const urlFileName = getFileNameFromUrl(url)
    let finalFileName

    if (urlFileName) {
      // 如果URL中有文件名，使用 人员姓名 + URL中的扩展名
      const urlExtension = getFileExtensionFromUrl(url)
      finalFileName = `${fileName}${urlExtension || ''}`
    } else {
      // 如果URL中没有文件名，根据Content-Type或URL自动检测文件扩展名
      let fileExtension =
        getFileExtensionFromUrl(url) || getFileExtensionFromContentType(contentType)

      // 如果没有检测到扩展名，使用默认扩展名
      if (!fileExtension) {
        fileExtension = '.bin'
      }

      finalFileName = `${fileName}${fileExtension}`
    }

    console.log(`最终文件名: ${finalFileName}`)

    // 创建下载链接
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = finalFileName
    link.style.display = 'none'

    // 添加下载完成监听
    link.onclick = () => {
      setTimeout(() => {
        if (document.body.contains(link)) {
          document.body.removeChild(link)
        }
        window.URL.revokeObjectURL(downloadUrl)
      }, 2000)
    }

    document.body.appendChild(link)
    link.click()

    // 清理资源
    setTimeout(() => {
      if (document.body.contains(link)) {
        document.body.removeChild(link)
      }
      window.URL.revokeObjectURL(downloadUrl)
    }, 100)

    console.log(`✅ ${finalFileName} 下载完成`)
  } catch (error) {
    console.error('下载失败:', error)

    // 备用方案：新窗口打开（需要服务端支持CORS）
    try {
      const fallbackWindow = window.open(url, '_blank')
      if (!fallbackWindow) {
      }
    } catch (fallbackError) {
      console.error('备用下载方案也失败:', fallbackError)
    }
  }
}

// 从URL中提取文件名（不包含扩展名）
const getFileNameFromUrl = (url) => {
  try {
    const urlObj = new URL(url)
    const pathname = urlObj.pathname
    const lastSlashIndex = pathname.lastIndexOf('/')
    const fileName = pathname.substring(lastSlashIndex + 1)

    // 移除扩展名，只返回文件名部分
    const lastDotIndex = fileName.lastIndexOf('.')
    if (lastDotIndex !== -1) {
      return fileName.substring(0, lastDotIndex)
    }
    return fileName
  } catch (error) {
    console.warn('从URL提取文件名失败:', error)
  }
  return null
}

// 从URL中提取文件扩展名
const getFileExtensionFromUrl = (url) => {
  try {
    const urlObj = new URL(url)
    const pathname = urlObj.pathname
    const lastDotIndex = pathname.lastIndexOf('.')
    if (lastDotIndex !== -1 && lastDotIndex < pathname.length - 1) {
      return pathname.substring(lastDotIndex)
    }
  } catch (error) {
    console.warn('解析URL失败:', error)
  }
  return null
}

// 根据Content-Type获取文件扩展名
const getFileExtensionFromContentType = (contentType) => {
  if (!contentType) return null

  const typeMap = {
    'application/pdf': '.pdf',
    'application/msword': '.doc',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
    'application/vnd.ms-excel': '.xls',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
    'application/vnd.ms-powerpoint': '.ppt',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx',
    'text/plain': '.txt',
    'text/csv': '.csv',
    'image/jpeg': '.jpg',
    'image/png': '.png',
    'image/gif': '.gif',
    'image/webp': '.webp',
    'application/zip': '.zip',
    'application/x-rar-compressed': '.rar',
    'application/x-7z-compressed': '.7z',
    'video/mp4': '.mp4',
    'video/avi': '.avi',
    'video/quicktime': '.mov',
    'audio/mpeg': '.mp3',
    'audio/wav': '.wav',
    'application/json': '.json',
    'application/xml': '.xml',
    'text/html': '.html',
    'text/css': '.css',
    'application/javascript': '.js',
  }

  // 查找匹配的Content-Type
  for (const [type, extension] of Object.entries(typeMap)) {
    if (contentType.toLowerCase().includes(type.toLowerCase())) {
      return extension
    }
  }

  return null
}

// 显示角色详情
const showRoleDetail = (personRowid) => {
  selectedRole.value = personRowid
  dialogVisible.value = true
}

const getCustomer = (project) => {
  const customerData = project?.['686f297f781faa1ac7bbda20']
  if (customerData === '[]') {
    return ''
  }

  try {
    const parsedData = JSON.parse(customerData)
    const sourceValue = JSON.parse(parsedData[0].sourcevalue)
    return sourceValue['686f26e30323e30ac5121f7e'] || ''
  } catch (error) {
    return ''
  }
}

// 获取角色状态标签
const getRoleStatusLabel = (person, roleType = null) => {
  const personName = person['686e0c6fd9147824a38a6294']
  if (!personName) return ''

  // 使用传入的roleType，如果没有传入则使用当前选中的分类
  const currentRoleType = roleType || selectedCategory.value

  // 检查是否在已选中列表中，并且角色类型匹配
  const isSelected = selectRoleList.value.some(
    (item) =>
      item['68aee8753f18dc08c56c82c4'] === personName &&
      item['68b84c036617217ad4227f51'] === currentRoleType,
  )
  if (isSelected) return '已选中'

  // 检查是否在已退回列表中，并且角色类型匹配
  const isGiveback = givebackRoleList.value.some(
    (item) =>
      item['68aee8753f18dc08c56c82c4'] === personName &&
      item['68b84c036617217ad4227f51'] === currentRoleType,
  )
  if (isGiveback) return '已退回'

  return ''
}

// 获取角色状态样式类
const getRoleStatusClass = (person, roleType = null) => {
  const personName = person['686e0c6fd9147824a38a6294']
  if (!personName) return ''

  // 使用传入的roleType，如果没有传入则使用当前选中的分类
  const currentRoleType = roleType || selectedCategory.value

  // 检查是否在已选中列表中，并且角色类型匹配
  const isSelected = selectRoleList.value.some(
    (item) =>
      item['68aee8753f18dc08c56c82c4'] === personName &&
      item['68b84c036617217ad4227f51'] === currentRoleType,
  )
  if (isSelected) return 'status-selected'

  // 检查是否在已退回列表中，并且角色类型匹配
  const isGiveback = givebackRoleList.value.some(
    (item) =>
      item['68aee8753f18dc08c56c82c4'] === personName &&
      item['68b84c036617217ad4227f51'] === currentRoleType,
  )
  if (isGiveback) return 'status-giveback'

  return ''
}

const getProject = async () => {
  const projectId = route.query.id
  if (projectId) {
    const result = await apiService.getRowById({
      rowId: route.query.id,
      worksheetId: ApiService.WORKSHEETENUM.PROJECTS,
    })
    console.log('getProject:', result)
    project.value = result
  }
}

const getDemandCeshi = async () => {
  const Res1 = await apiService.getFilterRows({
    worksheetId: '6876257b872d9db2c7ba5292',
    filters: [
      {
        controlId: '686e48ea1f42f2639e1b9075',
        dataType: 29,
        spliceType: 1,
        filterType: 24,
        value: project.value['rowid'],
      },
    ],
  })
  console.log('需求明细RowidList:', Res1)

  const resRowidList = Res1.rows.map((item) => {
    return item['rowid']
  })

  console.log('resRowidList:', resRowidList)

  const Res2 = await apiService.getFilterRows({
    worksheetId: '6876257b872d9db2c7ba5292',
    filters: [
      {
        controlId: 'rowid',
        dataType: 2,
        spliceType: 1,
        filterType: 2,
        values: resRowidList,
      },
    ],
  })
  console.log('需求明细:', Res2)

  itemList.value = Res2.rows
    .map((item) => {
      return {
        classify: item['68917536f6303e511c9ab05f'],
        type: item['686f2308f11e0126aeb367d7'],
        personNum: item['686e48ea1f42f2639e1b907b'],
        demand: JSON.parse(item['68afcc636b50e0d4f7a767b4']).map((item) => {
          return item.name
        }),
        work: item['686e48ea1f42f2639e1b907f'],
      }
    })
    .filter((item) => item.classify !== '二类角色') // 过滤掉"带队"角色
  console.log('itemList:', itemList.value)

  // 设置默认选中第一个分类
  if (itemList.value.length > 0) {
    selectedCategory.value = itemList.value[0].type
  }
}

const getDemand = async () => {
  console.log('项目名称')

  console.log(project.value['686df5d4fa20ded33c042478'])

  const registerRes = await apiService.getFilterRows({
    worksheetId: '6876257b872d9db2c7ba5292',
    filters: [
      {
        controlId: '68749ae8137fa7472c37b541',
        dataType: 2,
        spliceType: 1,
        filterType: 2,
        value: project.value['686df5d4fa20ded33c042478'],
      },
    ],
  })

  console.log('获取项目明细')
  console.log(registerRes.rows)
  demand.value = registerRes.rows

  // 获取所有要求
  demand.value.forEach((item) => {
    demandSet.value.add(item['686e48ea1f42f2639e1b907e'])
    const demandData = JSON.parse(item['68afcc636b50e0d4f7a767b4'])
    demandData.forEach((acc) => demandSet.value.add(acc.name))
  })
  console.log('demandSet:', demandSet.value)
  // 获取所有工作内容
  demand.value.forEach((item) => {
    workSet.value.add(item['686e48ea1f42f2639e1b907f'])
  })
  console.log('workSet:', workSet.value)

  // 返回项目明细需求的特定对象
  demandToRole.value = demand.value.map((item) => {
    return {
      type: item['686f2308f11e0126aeb367d7'],
      total: item['686e48ea1f42f2639e1b907b'],
    }
  })

  console.log('demandToRole:', demandToRole.value)
}

const getRoleStatus = async () => {
  const result = await apiService.getRoleStatus({
    projectRowid: project.value['rowid'],
    userRowid: userStore.userRowid,
  })

  console.log('getRoleStatus:', JSON.parse(result.data))
  selectRoleList.value = JSON.parse(result.data).filter(
    (item) => item['68b7eb8d6617217ad42266b1'] == '已选中',
  )

  givebackRoleList.value = JSON.parse(result.data).filter(
    (item) => item['68b7eb8d6617217ad42266b1'] == '推荐失败',
  )

  console.log('selectRoleList:', selectRoleList.value)
  console.log('givebackRoleList:', givebackRoleList.value)

  // 构建已选中姓名集合
  const nameSet = new Set()
  selectRoleList.value.forEach((item) => {
    const name = item && item['68aee8753f18dc08c56c82c4']
    if (name) nameSet.add(name)
  })
  selectedNameSet.value = nameSet

  // 如果当前已有候选人列表，立即更新卡片状态
  if (candidateList.value && candidateList.value.length > 0) {
    candidateList.value.forEach((person) => {
      const personName = person['686e0c6fd9147824a38a6294']
      if (personName && selectedNameSet.value.has(personName)) {
        person['68761720096a775fc5332e94'] = '已选中'
      }
    })
  }
}

const getRoleList = async () => {
  console.log('project.rowid:', project.value['rowid'])

  const result = await apiService.getRoleList({
    hook: 'NjhiODIwMjBkZGE0MTI2NGYwZjRhNTRi',
    projectRowid: project.value['rowid'],
  })

  console.log('getRoleList:', JSON.parse(result.data))

  // 聚合结果
  const map = new Map()

  JSON.parse(result.data).forEach((item) => {
    if (!map.has(item['68b84c036617217ad4227f51'])) {
      map.set(item['68b84c036617217ad4227f51'], [])
      map.get(item['68b84c036617217ad4227f51']).push(item['68aee8753f18dc08c56c82c4'])
    } else {
      map.get(item['68b84c036617217ad4227f51']).push(item['68aee8753f18dc08c56c82c4'])
    }
  })

  const result1 = Array.from(map, (item) => ({
    type: item[0],
    list: item[1],
  }))
  console.log('result1')
  console.log(result1)

  // 使用 Promise.all 来并行处理所有异步请求
  const roleListPromises = result1.map(async (item) => {
    const res = await apiService.getFilterRows({
      worksheetId: '6876257b872d9db2c7ba5297',
      filters: [
        {
          controlId: '686e0c6fd9147824a38a6294',
          dataType: 29,
          spliceType: 1,
          filterType: 2,
          values: item['list'],
        },
      ],
    })

    console.log('roleListPromises:', res)

    return {
      type: item['type'],
      list: res.rows,
    }
  })

  // 等待所有请求完成
  const roleListResults = await Promise.all(roleListPromises)

  console.log('roleListResults:', roleListResults)
  roleList.value = roleListResults

  // 设置默认选中的分类和候选人列表
  if (roleListResults.length > 0) {
    selectedCategory.value = roleListResults[0]['type']

    // 清空并设置候选人列表
    candidateList.value = []
    roleListResults[0]['list'].forEach((person) => {
      candidateList.value.push({
        ...person,
        userSelected: false,
      })
    })
  }

  console.log('selectedCategory:', selectedCategory.value)
}

onMounted(async () => {
  console.log('页面加载完毕')

  // 打印路由参数
  console.log('项目对象:', route.query.project ? JSON.parse(route.query.project) : null)
  console.log('项目对象id:', route.query.id)

  await getProject() //获取项目信息

  await getDemandCeshi() //获取需求明细

  // await getDemand() //获取需求信息

  await getRoleList() //获取角色列表

  await getRoleStatus() //获取角色状态
})

// 获取更多（当总选中人数不足时，用户点击"获取更多"）
const handleGetMore = async () => {
  console.log('获取更多')
  // 检查所有角色类型的人数是否都符合需求
  // 使用 itemList 数据源替代 uniqueRoleTypes 和 demandToRole
  for (const item of itemList.value) {
    const roleTypeName = item.type
    const currentSelectedCount = selectedRolesStats.value[roleTypeName] || 0
    const requiredCount = parseInt(item.personNum) || 0

    // 如果任何一个角色类型的人数超过需求，就阻止提交
    if (currentSelectedCount > requiredCount) {
      console.log('handleGetMore')

      console.log('currentSelectedCount:', currentSelectedCount)
      console.log('requiredCount:', requiredCount)
      ElMessage.warning(`${roleTypeName}类别人数已满，请先取消其他选择`)
      return
    }
  }
  // 执行确认选中逻辑
  await selectRecommendedPersons('获取更多')
}

// 新增：确认选中对话框相关变量
const confirmDialogVisible = ref(false)
const confirmDialogTitle = ref('')
const confirmDialogContent = ref('')
const confirmDialogType = ref('info') // info, success, warning, error
const confirmDialogButtons = ref({
  confirm: '确认',
  cancel: '取消',
})
const confirmDialogCallback = ref(null)

// 处理对话框关闭前的逻辑
const handleDialogBeforeClose = (done) => {
  // 直接关闭对话框，不执行任何业务逻辑
  done()
}

// 获取当前分类的人员数量
const getCurrentCategoryPersonNum = () => {
  const currentItem = itemList.value.find((item) => item.type === selectedCategory.value)
  return currentItem ? currentItem.personNum : 0
}

// 获取当前分类的要求
const getCurrentCategoryDemand = () => {
  const currentItem = itemList.value.find((item) => item.type === selectedCategory.value)
  return currentItem ? currentItem.demand.join('、') : ''
}

// 获取当前分类的工作内容
const getCurrentCategoryWork = () => {
  const currentItem = itemList.value.find((item) => item.type === selectedCategory.value)
  return currentItem ? currentItem.work : ''
}

// 在 script setup 中添加状态变量
const isExportMode = ref(false) // 是否为导出模式

// 新增：获取当前分类的已选择人数
const currentCategorySelectedCount = computed(() => {
  return filteredCandidateList.value.filter((person) => person.userSelected).length
})
</script>

<style scoped>
.location {
  color: #919090;
  font-size: 12px;
  margin-left: 10px;
}

.project-container {
  padding: 20px;
  background: #ffffff;
  height: 100vh;
  font-family: 'Microsoft YaHei', sans-serif;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  max-width: 1600px;
  margin: 0 auto;
}

/* 项目头部信息 */
.project-header {
  border-bottom: none;
  padding: 20px;
  border-radius: 10px;
}

.project-title-row {
  display: flex;
  align-items: flex-end;
  justify-content: flex-start;
  margin-bottom: 8px;
  gap: 20px;
  width: 100%;
}

.project-title {
  display: flex;
  align-items: center;
  gap: 15px;
}

.project-badge {
  background: #ff8800;
  color: white;
  padding: 4px 16px;
  border-radius: 4px;
  font-size: 16px;
}

.project-title h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
  font-weight: 600;
  max-width: 400px; /* 固定宽度 */
  white-space: nowrap; /* 防止换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
  font-size: clamp(16px, 4vw, 24px); /* 响应式字体大小，最小16px，最大24px */
}

.project-meta {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 20px;
  margin-bottom: 15px;
  color: #666;
  font-size: 14px;
  line-height: 1;
}

.project-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: nowrap;
}

.title-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: nowrap;
  position: relative;
  top: 5px;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

/* 将返回按钮推到最右侧 */
.return-btn {
  margin-left: auto;
}

.title-actions::-webkit-scrollbar {
  display: none;
}

.company-text {
  color: #949496;
  font-size: 14px;
}

.current-user-company {
  color: #666;
  font-size: 12px;
  margin-left: 10px;
  padding: 2px 8px;
  background: #f5f5f5;
  border-radius: 4px;
}

.requirements {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 20px;
}

.req-left {
  display: flex;
  flex: 1 1 0;
  min-width: 0;
  flex-direction: column;
  gap: 8px;
}

.req-roles {
  display: flex;
  align-items: center;
  gap: 12px;
}

.req-role {
  color: #333;
  font-size: 14px;
}

.req-role_red {
  color: #ea4096;
  font-size: 14px;
}
.role_card {
  width: 100%;
}
.role_top {
  padding: 10px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.role_card_top {
  width: 100%;
  display: flex;
  justify-content: start;
  gap: 50px;
}

.req-constraints {
  color: #666;
  font-size: 13px;
  display: inline-block;
  max-width: 39ch;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.req-center {
  flex: 1 1 0;
  min-width: 0;
  display: flex;
  align-items: center;
  color: #666;
  font-size: 13px;
}
.req-work {
  color: #666;
  font-size: 13px;
  display: inline-block;
  max-width: 39ch;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.req-right {
  gap: 10px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-end;
  align-self: stretch;
  flex: 1 1 0;
  min-width: 0;
}

.right-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: flex-end;
  margin-left: auto;
}

.action-btn {
  padding: 8px 18px;
  border: none;
  background: white;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #ddd;
  white-space: nowrap;
  min-width: fit-content;
  flex-shrink: 0;
}

.action-btn:hover {
  border-color: #ff69b4;
  color: #ff69b4;
}

/* 特定类型按钮样式 */
.action-btn.ceremony {
  background: #fddbec;
  border: none;
  color: #333;
}

.action-btn.part-time {
  background: #dbe9fb;
  border: none;
  color: #333;
}
.project-item {
  color: #eb4498;
  font-weight: 800;
}

.action-btn.team-lead {
  background: #fbe5dc;
  border: none;
  color: #333;
}

.export-btn {
  padding: 6px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  font-size: 13px;
  color: #666;
  cursor: pointer;
}

.recommend-btn {
  margin-left: 10px;
  padding: 6px 16px;
  background: #ea4096;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.recommend-btn:hover {
  background: #e55aa0;
}

/* 退回按钮样式 */
.return-btn-style {
  background: #f56c6c !important;
  color: white !important;
}

.return-btn-style:hover {
  background: #f78989 !important;
}

/* 标签导航 */
.tab-navigation {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 20px;
  overflow-x: auto;
  padding-bottom: 5px;
  margin-top: 30px;
  scrollbar-width: thin;
  scrollbar-color: #ddd transparent;
}

.tab-navigation::-webkit-scrollbar {
  height: 4px;
}

.tab-navigation::-webkit-scrollbar-track {
  background: transparent;
}

.tab-navigation::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 2px;
}

.tab-scroll-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
}

.tab-scroll-icon {
  width: 16px;
  height: 16px;
  display: inline-block;
  background-color: #c2c2c2;
  mask-image: url('@/assets/images/右箭头.svg');
  -webkit-mask-image: url('@/assets/images/右箭头.svg');
  mask-size: contain;
  -webkit-mask-size: contain;
  mask-repeat: no-repeat;
  -webkit-mask-repeat: no-repeat;
  mask-position: center;
  -webkit-mask-position: center;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: #f5f5f5;
  border-radius: 20px;
  font-size: 13px;
  color: #666;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.tab-item.active {
  background: #ff69b4;
  color: white;
}

.tab-item:hover:not(.active) {
  background: #ebebeb;
}

.tab-icon {
  font-size: 12px;
}

/* 主要内容区域 */
.content-area {
  background-color: #fdf3f4;
  display: flex;
  gap: 20px;
  flex: 1;
  overflow: hidden;
}

/* 左侧分类菜单 */
.category-sidebar {
  width: 40px;
  flex-shrink: 0;
  background: linear-gradient(to bottom, #e8e4f0 0%, #eddbe7 50%, #fae6e9 100%);
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: center;
  padding: 20px 0;
  height: 100%;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 30px;
}

.category-item:hover {
  background: rgba(255, 255, 255, 0.2);
}

.category-item.active .category-text {
  color: #000;
}

.category-text {
  writing-mode: vertical-rl;
  text-orientation: mixed;
  font-size: 14px;
  color: #999999;
  font-weight: 500;
  letter-spacing: 2px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 人员卡片网格 */
.personnel-grid {
  background-color: #fdf3f4;
  flex: 1;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-auto-rows: max-content;
  gap: 20px;
  padding: 12px;
  overflow-y: auto;
  height: 100%;
  align-content: start;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 隐藏Webkit浏览器的滚动条 */
.personnel-grid::-webkit-scrollbar {
  display: none;
}

/* 状态标签 */
.selected-label {
  position: absolute;
  top: 0;
  left: 0;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 8px 0 0 0;
  z-index: 3;
  font-weight: 500;
  transition: opacity 0.3s ease;
}

/* 已选中状态 */
.status-selected {
  background: #eb4196;
  color: white;
  box-shadow: 0 2px 4px rgba(235, 65, 150, 0.3);
}

/* 已退回状态 */
.status-giveback {
  background: #f56c6c;
  color: white;
  box-shadow: 0 2px 4px rgba(245, 108, 108, 0.3);
}

.personnel-card {
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: visible;
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.personnel-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  border-color: #f28ec0;
}

/* 选择框 - 定位到右上角边框上 */
.selection-mark {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid #ddd;
  background: white;
  z-index: 2;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.selection-mark.selected {
  background: #ff69b4;
  border-color: #ff69b4;
}

.selection-mark.selected::after {
  content: '✓';
  color: white;
  font-size: 12px;
  font-weight: bold;
}

/* 选择框置灰状态 */
.selection-mark.disabled {
  background: #f5f5f5;
  border-color: #ddd;
  cursor: not-allowed;
  opacity: 0.6;
}

.selection-mark.disabled:hover {
  background: #f5f5f5;
  border-color: #ddd;
  transform: none;
}

.avatar-container {
  position: relative;
  padding: 15px 15px 10px;
}

/* 正方形头像 */
.avatar {
  width: 100%;
  aspect-ratio: 1;
  border-radius: 6px;
  background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

/* 占位符头像样式 */
.avatar:not([style*='url'])::before {
  content: '👤';
  font-size: 40px;
  color: #ccc;
  opacity: 0.8;
}

.avatar:not([style*='url'])::after {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% {
    left: -100%;
  }
  100% {
    left: 100%;
  }
}

.deal-badge {
  position: absolute;
  bottom: 4px;
  right: 4px;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #eb4196;
  background: rgba(255, 255, 255, 0.9);
  white-space: nowrap;
  backdrop-filter: blur(4px);
}

.personnel-info {
  padding: 0 15px 15px;
}

.name-section {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 8px;
}

.name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.gender {
  font-size: 14px;
  color: #ff69b4;
  font-weight: 900;
}

.stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 4px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 11px;
  color: #333;
  font-weight: 500;
  margin-bottom: 2px;
}

.stat-label {
  display: block;
  font-size: 10px;
  color: #999;
}

/* 加载状态样式 */
.loading-indicator,
.initial-loading-indicator,
.no-more-indicator,
.empty-indicator {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 14px;
}

.loading-indicator p {
  margin: 0;
  color: #ff69b4;
}

.initial-loading-indicator p {
  margin: 0;
  color: #ff69b4;
  font-weight: 500;
}

.no-more-indicator p {
  margin: 0;
  color: #999;
}

.empty-indicator p {
  margin: 0;
  color: #ccc;
}

.secondary-btn {
  background-color: white;
  border-color: #dcdfe6;
  color: #606266;
}

.secondary-btn:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #606266;
}
.selection-summary-box {
  max-width: 680px;
  line-height: 1.6;
}
.selection-summary-box .summary-title {
  font-weight: 600;
  margin-bottom: 8px;
}
.selection-summary-box .summary-line {
  color: #606266;
  font-size: 14px;
  margin: 10px 0;
}
.selection-summary-box .summary-description {
  color: #909399;
  font-size: 13px;
  margin: 8px 0 4px 0;
  font-style: italic;
}
.selection-summary-box .el-message-box__btns .el-button {
  padding: 10px 16px;
}

.confirm-dialog-content {
  padding: 10px 0;
}

.confirm-dialog-text {
  line-height: 1.6;
  color: #606266;
  font-size: 14px;
  white-space: pre-line;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 成功按钮样式 */
.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.el-button--success:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

/* 确认选中按钮置灰样式 */
.recommend-btn.disabled {
  background: #c0c4cc !important;
  color: #a8abb2 !important;
  cursor: not-allowed !important;
  border: 1px solid #c0c4cc !important;
}

.recommend-btn.disabled:hover {
  background: #c0c4cc !important;
  color: #a8abb2 !important;
}

.exit-export-btn {
  margin-left: 10px;
  padding: 6px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  font-size: 13px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
}

.exit-export-btn:hover {
  border-color: #f56c6c;
  color: #f56c6c;
}
</style>
